package indi.jp.project.base.service.impl;

import indi.jp.project.base.entity.Department;
import indi.jp.project.base.service.DepartmentService;
import indi.jp.project.core.dao.BaseDao;
import org.springframework.stereotype.Service;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class DepartmentServiceImpl implements DepartmentService {

    private BaseDao baseDao;

    public DepartmentServiceImpl(BaseDao baseDao) {
        this.baseDao = baseDao;
    }

    @Override
    public Map<String, Object> queryGrid(Department entity) throws SQLException {
        Map<String, Object> map = new HashMap<>();
        List<Department> list = baseDao.queryList("departmentMapper.queryList", entity);
        int count = baseDao.queryCount("departmentMapper.queryCount", entity);
        map.put("grid", list);
        map.put("total", count);
        return map;
    }

    @Override
    public int save(Department entity) throws SQLException {
        if ("".equals(entity.getId())) {
            String code = entity.getCode();
            Object obj = baseDao.findByObject("departmentMapper.queryMaxBrotherNum", entity.getpId());
            int num = 0;
            if (obj != null) {
                num = (int) obj;
            }
            num = num + 1;
            String numStr = String.format("%03d", num);
            code = code + "-" + numStr;
            entity.setNum(num);
            entity.setCode(code);
            return baseDao.insert("departmentMapper.save", entity);
        } else {
            return baseDao.update("departmentMapper.edit", entity);
        }
    }

    @Override
    public int deleteByCode(String id) throws SQLException {
        return baseDao.delete("departmentMapper.deleteByCode", id);
    }

    @Override
    public List<Department> queryTreeList(Department entity) throws SQLException {
        return baseDao.queryList("departmentMapper.queryTreeList", entity);
    }
}
